package top.gytf.unifiedcall.support.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.gytf.unifiedcall.common.api.ApiDefinitionFactory;
import top.gytf.unifiedcall.common.contract.ApiContractManager;
import top.gytf.unifiedcall.common.contract.ApiContractManagerImpl;
import top.gytf.unifiedcall.common.contract.ApiContractReader;
import top.gytf.unifiedcall.common.detial.UnifiedCallPackageLoader;
import top.gytf.unifiedcall.common.detial.UnifiedCallPackageManager;
import top.gytf.unifiedcall.common.detial.UnifiedCallPackageManagerImpl;
import top.gytf.unifiedcall.common.support.ApiDefinitionFactoryImpl;
import top.gytf.unifiedcall.common.support.SpiUnifiedCallPackageLoader;
import top.gytf.unifiedcall.common.support.UnifiedCallApiContractReader;

import java.util.List;

/**
 * Common模块的自动装配
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
public class UnifiedCallCommonAutoConfiguration {
    @Bean
    public UnifiedCallApiContractReader unifiedCallApiContractReader(UnifiedCallPackageManager unifiedCallPackageManager) {
        return new UnifiedCallApiContractReader(unifiedCallPackageManager);
    }

    @Bean(initMethod = "initialize", destroyMethod = "destroy")
    @ConditionalOnMissingBean(ApiContractManager.class)
    public ApiContractManager apiContractManager(List<ApiContractReader> apiContractReaders) {
        log.debug("注入默认ApiContractManager，使用自定义ApiContractReader：{}", apiContractReaders);
        ApiContractManagerImpl manager = new ApiContractManagerImpl();
        manager.setApiContractReaders(apiContractReaders);
        return manager;
    }

    @Bean
    public UnifiedCallPackageLoader spiUnifiedCallPackageLoader() {
        return new SpiUnifiedCallPackageLoader();
    }

    @Bean(initMethod = "initialize", destroyMethod = "destroy")
    @ConditionalOnMissingBean(UnifiedCallPackageManager.class)
    public UnifiedCallPackageManager unifiedCallPackageManager(List<UnifiedCallPackageLoader> unifiedCallPackageLoaders) {
        log.debug("注入默认UnifiedCallPackageManager，使用自定义UnifiedCallPackageLoader：{}", unifiedCallPackageLoaders);
        return new UnifiedCallPackageManagerImpl(unifiedCallPackageLoaders);
    }

    @Bean
    @ConditionalOnMissingBean(ApiDefinitionFactory.class)
    public ApiDefinitionFactory apiDefinitionFactory(UnifiedCallPackageManager unifiedCallPackageManager, ApiContractManager apiContractManager) {
        log.debug("注入默认的ApiDefinitionFactory");
        return new ApiDefinitionFactoryImpl(apiContractManager, unifiedCallPackageManager);
    }
}
